package com.guazai.project.service.rpcimpl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.guazai.common.pojo.InterfaceInfo;
import com.guazai.common.pojo.UserInterfaceInfo;
import com.guazai.common.rpc.UserInterfaceInfoRPC;
import com.guazai.project.common.ErrorCode;
import com.guazai.project.exception.BusinessException;
import com.guazai.project.mapper.UserInterfaceInfoMapper;
import com.guazai.project.service.InterfaceInfoService;
import com.guazai.project.service.UserInterfaceInfoService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author qiteng
 */
@DubboService
public class userInterfaceInfoRPCImpl implements UserInterfaceInfoRPC {

    @Resource
    private UserInterfaceInfoMapper userInterfaceInfoMapper;

    @Resource
    private UserInterfaceInfoService userInterfaceInfoService;

    @Resource
    private InterfaceInfoService interfaceInfoService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateNum(long interfaceId, long userId, Integer updateNum) {
        //判断参数是否正确
        if (userId < 0 || interfaceId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //如果数据库中有这条数据，就修改---totalInvokes = totalInvokes + 1  leftNum = leftNum - 1
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("userId", userId);
        updateWrapper.eq("interfaceId", interfaceId);
        updateWrapper.setSql("totalInvokes = totalInvokes - " + updateNum + ", leftNum = leftNum + " + updateNum);
        if(!userInterfaceInfoService.update(updateWrapper)) {
            //如果没有，加插入数据---userId  interfaceId  totalInvokes = 1  leftNum = 99，直接返回调用结果
            UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
            userInterfaceInfo.setUserId(userId);
            userInterfaceInfo.setInterfaceId(interfaceId);
            userInterfaceInfo.setTotalInvokes(1);
            userInterfaceInfo.setLeftNum(99);
            return userInterfaceInfoMapper.insert(userInterfaceInfo) > 0;
        } else {
            return addInterfaceInvokes(interfaceId);
        }
    }

    public boolean addInterfaceInvokes(Long interfaceId) {
        //判断参数是否正确
        if (interfaceId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        //如果数据库中有这条数据，就修改---totalInvokes = totalInvokes + 1  leftNum = leftNum - 1
        UpdateWrapper<InterfaceInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", interfaceId);
        wrapper.setSql("totalInvokes = totalInvokes + 1");
        return interfaceInfoService.update(wrapper);
    }
}
